<?php

namespace app\proxy\model\supplier;

use app\common\model\region\Region as Region1;
use app\common\model\supplier\Supplier as SupplierModel;
use app\common\model\supplier\User as SupplierUserModel;
use app\common\model\user\User as UserModel;
use app\proxy\model\proxy\Region;
use app\shop\model\product\Product as ProductModel;
use app\supplier\model\supplier\User;

/**
 * 后台管理员登录模型
 */
class Supplier extends SupplierModel
{

    /**
     * 获取列表数据
     */
    // public function getList($params, $regionIds, $proxyId)
    // {
    //     $model = $this;
    //     if (isset($params['search']) && $params['search']) {
    //         $model = $model->where('name', 'like', '%' . $params['search'] . '%');
    //     }
    //     if (isset($params['is_audit'])) {
    //         $model = $model->where('is_audit', $params['is_audit']);
    //     }
    //     // 查询列表数据
    //     return $model->with(['logo', 'superUser', 'business'])
    //         ->where('is_delete', '=', '0')
    //         ->where(function ($query) use ($params, $regionIds, $proxyId) {
    //             if (empty($params["proxy_id"])) {
    //                 $query->whereIn('region_id', $regionIds)->whereOr("province_id", "in", $regionIds)->whereOr("city_id", "in", $regionIds)->whereOr("proxy_id", $proxyId);
    //             } else {
    //                 $query->where("proxy_id", $params["proxy_id"]);
    //             }
    //         })
    //         ->withAttr('proxy_name', function ($value, $data) use ($proxyId) {
    //             return Region::getProxyName($data, $proxyId);
    //         })->withAttr('can_edit', function ($value, $data) use ($proxyId) {
    //             return $data["proxy_id"] == $proxyId ? 1 : 0;
    //         })
    //         ->append(['proxy_name', 'can_edit'])
    //         ->order(['create_time' => 'desc'])
    //         ->paginate($params);
    // }

    /**
     * 获取列表数据
     */
    public function getList($params, $proxyId){
        $model = $this;
        if (isset($params['search']) && $params['search']) {
            $model = $model->where('name', 'like', '%' . $params['search'] . '%');
        }
        if (isset($params['is_audit'])) {
            $model = $model->where('is_audit', $params['is_audit']);
        }
        // 查询列表数据
        return $model->with(['logo', 'superUser', 'business'])
            ->where('is_delete', '=', '0')
            ->where("proxy_id", $proxyId)
            ->withAttr('proxy_name', function ($value, $data) use ($proxyId) {
                return Region::getProxyName($data, $proxyId);
            })->withAttr('can_edit', function ($value, $data) use ($proxyId) {
                return $data["proxy_id"] == $proxyId ? 1 : 0;
            })
            ->append(['proxy_name', 'can_edit'])
            ->order(['create_time' => 'desc'])
            ->paginate($params);
    }

    /**
     * 获取列表数据
     */
    // public function getSelectList($params, $regionIds, $proxyId)
    // {
    //     $model = $this;
    //     if (isset($params['search']) && $params['search']) {
    //         $model = $model->where('name', 'like', '%' . $params['search'] . '%');
    //     }
    //     if (isset($params['is_audit'])) {
    //         $model = $model->where('is_audit', $params['is_audit']);
    //     }
    //     // 查询列表数据
    //     return $model->where('is_delete', '=', '0')
    //         ->where(function ($query) use ($params, $regionIds, $proxyId) {
    //             if (empty($params["proxy_id"])) {
    //                 $query->whereIn('region_id', $regionIds)->whereOr("province_id", "in", $regionIds)->whereOr("city_id", "in", $regionIds)->whereOr("proxy_id", $proxyId);
    //             } else {
    //                 $query->where("proxy_id", $params["proxy_id"]);
    //             }
    //         })
    //         ->order(['create_time' => 'desc'])
    //         ->select();
    // }
    /**
     * 获取列表数据
     */
    public function getSelectList($params, $proxyId, $fields='*', $columnid='')
    {
        $model = $this;
        if (isset($params['search']) && $params['search']) {
            $model = $model->where('name', 'like', '%' . $params['search'] . '%');
        }
        if (isset($params['is_audit'])) {
            $model = $model->where('is_audit', $params['is_audit']);
        }
        if($columnid){
            // 查询列表数据
            return $model->where('is_delete', '=', '0')
                ->where(["proxy_id"=>$proxyId])
                ->order(['create_time' => 'desc'])
                ->column($columnid);
        }
        // 查询列表数据
        return $model->where('is_delete', '=', '0')
            ->where(["proxy_id"=>$proxyId])
            ->order(['create_time' => 'desc'])
            ->field($fields)
            ->select();
    }

    public static function getProxySupplierList($proxyId){
        return (new self)->getSelectList(['is_audit'=>1], $proxyId, 'shop_supplier_id', 'shop_supplier_id');
    }

    /*
    * 修改密码
    */
    public function editPass($data, $user)
    {
        $user_info = User::detail($user['shop_user_id']);
        if ($data['password'] != $data['confirmPass']) {
            $this->error = '密码错误';
            return false;
        }
        if ($user_info['password'] != salt_hash($data['oldpass'])) {
            $this->error = '两次密码不相同';
            return false;
        }
        $date['password'] = salt_hash($data['password']);
        $user_info->save($date);
        return true;
    }


    /**
     * 资金冻结
     */
    public function freezeMoney($money)
    {
        return $this->save([
            'money' => $this['money'] - $money,
            'freeze_money' => $this['freeze_money'] + $money,
        ]);
    }

    protected function checkRegion(&$supplier, $regions)
    {
        if (empty($supplier['region_id'][2])) {
            $this->error = '请选择区域';
            return false;
        }
        $province_id = $supplier['region_id'][0];
        $city_id = $supplier['region_id'][1];
        $county_id = $supplier['region_id'][2];
        $supplier['region_id'] = $county_id;


        if (!isset($regions[$county_id]) && !isset($regions[$city_id]) && !isset($regions[$province_id])) {
            $this->error = "区域不存在";
            return false;
        }
        $supplier["province_id"] = $province_id;
        $supplier["city_id"] = $city_id;
        $supplier["county_id"] = $county_id;
        $supplier["region_name"] = Region1::getMergerName($county_id);
        return true;
    }

    public function add($data, $regions, $proxy_id)
    {

        try {
            $supplier = $data['supplier'];
            if (SupplierUserModel::checkExist($supplier['user_name'])) {
                $this->error = '用户名已存在';
                return false;
            }

            if (!$this->checkRegion($supplier, $regions)) {
                return false;
            }
            // 用户是否已绑定
            $user = null;
            if ($supplier['user_id'] > 0) {
                $user = UserModel::detail($supplier['user_id']);
                if ($user['user_type'] != 1) {
                    $this->error = '该用户已绑定';
                    return false;
                }
                $isApply = $this->isApply($supplier['user_id']);
                if ($isApply) {
                    $this->error = '已经申请开店';
                    return false;
                }
            }
            // 添加供应商
            $supplier['app_id'] = self::$app_id;
            $supplier['proxy_id'] = $proxy_id;
            $this->startTrans();
            $this->save($supplier);
            // 添加登录用户
            $user_model = new SupplierUserModel();
            $user_model->save([
                'user_id' => $supplier['user_id'],
                'user_name' => $supplier['user_name'],
                'password' => salt_hash($supplier['password']),
                'real_name' => $supplier['user_name'],
                'shop_supplier_id' => $this['shop_supplier_id'],
                'is_super' => 1,
                'app_id' => self::$app_id,
            ]);
            // 后台添加的直接算审核通过
            if ($user) {
                $user->save([
                    'user_type' => 2
                ]);
            }
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 修改
     */
    public function edit($data, $regions, $proxy_id)
    {
        // 开启事务
        $this->startTrans();
        try {
            $supplier = $data['supplier'];
            $old_user_id = 0;
            if ($this['superUser']) {
                $old_user_id = $this['superUser']['user_id'];
            }
            if ($this['superUser'] && $supplier['user_name'] != $this['superUser']['user_name'] && SupplierUserModel::checkExist($supplier['user_name'])) {
                $this->error = '用户名已存在';
                return false;
            }
            if (!$this->checkRegion($supplier, $regions)) {
                return false;
            }
            // 用户是否已绑定
            $user = null;
            $userChange = false;
            if ($this['superUser'] && $supplier['user_id'] > 0 && $supplier['user_id'] != $this['superUser']['user_id']) {
                $user = UserModel::detail($supplier['user_id']);
                if ($user['user_type'] != 1) {
                    $this->error = '该用户已绑定';
                    return false;
                }
                $isApply = $this->isApply($supplier['user_id']);
                if ($isApply) {
                    $this->error = '已经申请开店';
                    return false;
                }
                $userChange = true;
            }
            // 修改供应商
            if ($this["is_audit"] == 2) {
                $supplier["is_audit"] = 0;
            }
            $supplier['proxy_id'] = $proxy_id;
            if ($this['proxy_id'] !== $proxy_id) {
                $this->error = '您无权编辑此商户';
                return false;
            }
            $this->save($supplier);
            // 修改登录用户
            $user_model = $this['superUser'];
            $user_data = [
                'user_id' => $supplier['user_id'],
                'user_name' => $supplier['user_name']
            ];
            if (isset($supplier['password']) && !empty($supplier['password'])) {
                $user_data['password'] = salt_hash($supplier['password']);
            }
            $user_model->save($user_data);
            // 后台添加的直接算审核通过
//            if ($userChange) {
//                $user->save([
//                    'user_type' => 2
//                ]);
//                //取消原来的
//                if ($old_user_id > 0) {
//                    (new UserModel())->where('user_id', '=', $old_user_id)->update([
//                        'user_type' => 1
//                    ]);
//                }
//            }
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 开启禁止
     */
    public function setRecycle($is_recycle)
    {
        // 开启事务
        $this->startTrans();
        try {
            if ($is_recycle == 1) {
                //产品下架
                (new ProductModel())->where('shop_supplier_id', '=', $this['shop_supplier_id'])->update(['product_status' => 20]);
            }
            //更改店铺状态
            $this->save(['is_recycle' => $is_recycle]);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }


    }

    /**
     * 软删除
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }
}